import { login, logout, getInfo, getMenu } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";
import { getMenuList, getPermissions } from "@/utils/router-methods";

const state = {
  token: getToken(),
  name: localStorage.getItem("nickName"),
  avatar: "",
  introduction: "",
  roles: [],
  userinfo: JSON.parse(localStorage.getItem("userInfo")),
  id: localStorage.getItem("userId"),
  menus: {},
  permissions: [],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_ID: (state, id) => {
    state.id = id;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo;
  },
  SET_MENUS: (state, menuList) => {
    state.menus = menuList;
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response;
          localStorage.setItem("userInfo", JSON.stringify(data));
          commit("SET_USERINFO", data);
          commit("SET_NAME", data.nick);
          commit("SET_ID", data.id);
          localStorage.setItem("nickName", data.nick);
          localStorage.setItem("userId", data.id);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMenu(state.id)
        .then((response) => {
          if (response.code == 0) {
            // reject("获取菜单失败");
            return;
          } else {
            const { data } = response;
            const menuList = getMenuList(data.menu);
            console.log("看menuList", menuList);
            const permissions = getPermissions(data.button_list);
            commit("SET_ROLES", "role");
            commit("SET_MENUS", menuList);
            commit("SET_PERMISSIONS", permissions);

            resolve(menuList);
          }
        })
        .catch((error) => {
          // reject(error);
          return;
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      localStorage.removeItem("userInfo");
      localStorage.removeItem("userId");
      localStorage.removeItem("nickName");
      commit("SET_USERINFO", {});
      commit("SET_ID", null);
      commit("SET_NAME", null);
      commit("SET_USERINFO", {});
      commit("SET_MENUS", {});
      commit("SET_ROLES", null);
      commit("SET_PERMISSIONS", []);
      resetRouter();
      dispatch("tagsView/delAllViews", null, { root: true });
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resolve();
    });
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + "-token";

    commit("SET_TOKEN", token);
    setToken(token);

    const { roles } = await dispatch("getInfo");

    resetRouter();

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch("permission/generateRoutes", roles, {
      root: true,
    });
    // dynamically add accessible routes
    router.addRoutes(accessRoutes);

    // reset visited views and cached views
    dispatch("tagsView/delAllViews", null, { root: true });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
